import java.util.PriorityQueue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86136
 * Date: 2025-04-21
 * Time: 12:43
 */
//实现一个固定线程个数的线程池
class MyThreadPool {
    //阻塞队列是天然线程安全
    private BlockingQueue<Runnable> queue = null;
    public MyThreadPool(int n) {
        //n表示固定的线程个数
        queue = new ArrayBlockingQueue<>(1000);
        //创建N个线程
        for (int i = 0; i < n; i++) {
            Thread thread = new Thread(() -> {
                try {
                    while (true) {
                        Runnable task = queue.take();//如果队列为空，就会阻塞等待
                        task.run();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            thread.start();
        }
    }
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }
}
public class Demo47 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool = new MyThreadPool(5);
        for (int i = 0; i < 1000; i++) {
            int id = i;
            pool.submit(() -> {
                System.out.println(Thread.currentThread().getName() + "id = " + id);
            });
        }
    }
}
